import gettext
import __builtin__


class I18N:
    def __init__(self, i18n_paths, default_lang):
        self.__i18n_paths = i18n_paths
        self.default_lang = default_lang

    def __call__(self, msg, lang=None):
        lang = self.default_lang if lang is None else lang
        bundle, separator, code = msg.partition('.')

        if bundle not in self.__i18n_paths:
            return 'No translations defined for domain \'{0}\'!'.format(bundle)

        path = self.__i18n_paths[bundle]
        try:
            tran = gettext.translation(bundle, path, [lang])
            return tran.ugettext(code)
        except:
            return 'Missing translation file for ' + msg


def install(i18n_paths, default_lang):
    __builtin__.__dict__['_'] = I18N(i18n_paths, default_lang)


def set_language(lang):
    f_i18n = __builtin__.__dict__['_']
    f_i18n.default_lang = lang
